package com.CST.logger;

import com.CST.common.constant.Constants;
import com.CST.entity.cb.Log;
import com.CST.mapper.dataplatform.LogMapper;
import com.CST.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 日志切面
 * @author ly
 * @since 2021-11-10
 */
@Aspect
@Component
@SuppressWarnings("all")
public class LogRecordAspect {

    @Autowired
    private LogMapper logMapper;
    //TODO 引入日志服务类入库
//    @Autowired
//    private LogService logService;

    /**
     * 配置切入点
     * 意思就是使用了@LogRecord的方法每次被请求都会检测到
     * @author ly
     * @date 2021/11/10 11:22
     */
//    @Pointcut("@annotation(com.cdss.common.annotation.LogRecord)")
    @Pointcut("@annotation(com.CST.logger.LogRecord)")
    public void logPointCut() {}


    /**
     * 可以理解为正常流程走完的后置切面
     * @param joinPoint 切点
     * @param jsonResult 返回对象
     * @author ly
     * @date 2021/11/10 13:25
     * @return void
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) { insertLog(joinPoint, null, jsonResult); }

    /**
     * 后置异常捕获
     * @param e 异常
     * @param joinPoint 切点
     * @author ly
     * @date 2021/11/10 13:07
     */
    @AfterThrowing(pointcut = "logPointCut()",throwing = "e")
    public void exceptionAfter(JoinPoint joinPoint,Exception e) { insertLog(joinPoint, e, null); }

    /**
     * 日志记录
     * (PS:里面有些参数可以要可以不要,我就先列举这些可能会用到的)
     * @param joinPoint 切点
     * @param e 异常对象
     * @param result 请求成功后返回的对象
     * @author ly
     * @date 2021/11/10 13:11
     */
    private void insertLog(JoinPoint joinPoint, Exception e, Object result) {
        //获得注解类内部信息,没获取到直接出切面
        LogRecord controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) { return; }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();

        //模块名或者功能名
        String module = controllerLog.module();

        //操作方式
        OperateType operateType = controllerLog.operateType();

        //获取请求过来的ip地址
        String ipAddress = getIpAddress(request);

        //被请求的类名
        String className = joinPoint.getTarget().getClass().getName();

        //被请求的方法名
        String methodName = joinPoint.getSignature().getName();

        String errorInfo =e.getMessage();

        //返回参数，这个地方异常的切面会没有返回结果
        String jsonResultString = JSON.toJSONString(result);

        //获取请求参数值
        Object[] args = joinPoint.getArgs();
        String requestParameter = JSON.toJSONString(args);

        //todo 日志记录 请表演↓ ( ▔•з•▔ )

        Log logInfo =new Log();
        logInfo.setModule(module);
        logInfo.setOperatetype(operateType.toString());
        logInfo.setIpaddress(ipAddress);
        logInfo.setClassname(className);
        logInfo.setMethodname(methodName);
        logInfo.setErrorinfo(errorInfo);
        logInfo.setParams(requestParameter);

        Date currDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
        logInfo.setCreatedon(sdf.format(currDate));
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        userName = userName == null || userName.isEmpty() ? "System" : userName;
        logInfo.setCreatedby(userName);
        logMapper.insert(logInfo);

    }


    /**
     * 获取请求过来的ip地址
     * @param request 请求对象
     * @author ly
     * @date 2021/11/10 13:17
     * @return java.lang.String
     */
    public static String getIpAddress(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return  "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }



    /**
     * 检测方法是否带有LogReCord注解
     * 题外话:
     *       这里可以获取其他的注解列如Swagger的@ApiOperation
     *       在获取注解内部参数,任由发挥
     * @param joinPoint 切点
     * @author ly
     * @date 2021/11/10 13:23
     * @return com.cdss.common.annotation.LogRecord
     */
    private LogRecord getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) { return method.getAnnotation(LogRecord.class); }
        return null;
    }

}
